package ch.zbw.sysventory.agent.scanner.impl;

import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;

import com.jacob.activeX.ActiveXComponent;
import com.jacob.com.Dispatch;
import com.jacob.com.EnumVariant;
import com.jacob.com.Variant;

import ch.zbw.sysventory.transport.model.Software;

public class SoftwareScanner {

	Logger logger = Logger.getRootLogger();

	public List<Software> getSoftwareList() {
		List<Software> softwareList = new ArrayList<Software>();

		try {
			ActiveXComponent axWMI = new ActiveXComponent(String.format("winmgmts:\\\\%s\\root\\CIMV2", "localhost"));
			Variant vCollection = axWMI.invoke("ExecQuery", new Variant("SELECT * FROM Win32_Product"));

			EnumVariant enumVariant = new EnumVariant(vCollection.toDispatch());
			Dispatch item = null;
			while (enumVariant.hasMoreElements()) {
				item = enumVariant.nextElement().toDispatch();

				Software software = new Software();

				software.setName(Dispatch.call(item, "Name").toString().trim());
				software.setVersion(Dispatch.call(item, "Version").toString().trim());

				softwareList.add(software);
			}
		} catch (Exception e) {
			logger.error("Cannot read software list: " + e.getMessage(), e);
		}

		return softwareList;
	}
}
